package com.test;

import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhouzhigang
 *
 */
public class HttpsHttpClientUtils {
	private static final Logger logger = LoggerFactory.getLogger(HttpsHttpClientUtils.class);

	/**
	 * @Title: getNewHttpClient
	 * @Description: Methods Description
	 * @param @return
	 * @return HttpClient
	 * @throws
	 */

	private static HttpClient getNewHttpClient() {
		try {
			KeyStore trustStore = KeyStore.getInstance(KeyStore
					.getDefaultType());
			trustStore.load(null, null);
			SSLSocketFactory sf = new SSLSocketFactory(trustStore);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			HttpParams params = new BasicHttpParams();
			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			registry.register(new Scheme("https", sf, 443));
			ClientConnectionManager ccm = new ThreadSafeClientConnManager(
					params, registry);
			return new DefaultHttpClient(ccm, params);
		} catch (Exception e) {
			return new DefaultHttpClient();
		}
	}

	/**
	 * @param 获取Https请求返回的流数据
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> getImageStream(String url)
			throws Exception {
		DefaultHttpClient httpclient = (DefaultHttpClient) getNewHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,  150000);//连接时间150s
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,150000);//数据传输时间150s
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// Secure Protocol implementation.
			SSLContext ctx = SSLContext.getInstance("SSL");
			// Implementation of a trust manager for X509 certificates
			X509TrustManager tm = new X509TrustManager() {

				public void checkClientTrusted(X509Certificate[] xcs,
						String string) throws CertificateException {

				}

				public void checkServerTrusted(X509Certificate[] xcs,
						String string) throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory ssf = new SSLSocketFactory(ctx);
			ClientConnectionManager ccm = httpclient.getConnectionManager();
			// register https protocol in httpclient's scheme registry
			SchemeRegistry sr = ccm.getSchemeRegistry();
			sr.register(new Scheme("https", 443, ssf));

			HttpGet httpGet = new HttpGet(url);
			HttpResponse response = httpclient.execute(httpGet);
			Header[] headers = response.getAllHeaders();
			if(headers == null || headers.length < 1){
				return null;
			}
			String fileExt = ".png";
			for (int i = 0; i < headers.length; i++) {
				System.out.println(headers[i].getName() + "===>>>"
						+ headers[i].getValue());
				if ("Content-Type".equals(headers[i].getName())
						&& "image/jpeg".equals(headers[i].getValue())) {
					fileExt = ".jpg";
				} else if ("Content-Type".equals(headers[i].getName())
						&& "image/png".equals(headers[i].getValue())) {
					fileExt = ".png";
				}
			}
			logger.info("fileExt===>>>>>fileExt=" + fileExt);
			map.put("fileExt", fileExt);
			map.put("imageStream", response.getEntity().getContent());
			return map;
		} catch (Exception e) {
			logger.error("getImageStream===>>>>发生异常！",e);
			throw e;
		}

	}

	/**
	 * 只是获取图片二进制流
	 * 
	 * @author zhouzhigang
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static InputStream getSingleImageStream(String url) throws Exception {
		DefaultHttpClient httpclient = (DefaultHttpClient) getNewHttpClient();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// Secure Protocol implementation.
			SSLContext ctx = SSLContext.getInstance("SSL");
			// Implementation of a trust manager for X509 certificates
			X509TrustManager tm = new X509TrustManager() {

				public void checkClientTrusted(X509Certificate[] xcs,
						String string) throws CertificateException {

				}

				public void checkServerTrusted(X509Certificate[] xcs,
						String string) throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			ctx.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory ssf = new SSLSocketFactory(ctx);
			ClientConnectionManager ccm = httpclient.getConnectionManager();
			// register https protocol in httpclient's scheme registry
			SchemeRegistry sr = ccm.getSchemeRegistry();
			sr.register(new Scheme("https", 443, ssf));

			HttpGet httpGet = new HttpGet(url);
			HttpResponse response = httpclient.execute(httpGet);
			return response.getEntity().getContent();
		} catch (Exception e) {
			logger.error("url="+url+"==>>>>getSingleImageStream===>>>>发生异常！",e);
			throw e;
		}

	}

	/**
	 * 测试方法
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		// DefaultHttpClient httpclient = (DefaultHttpClient)
		// getNewHttpClient();
		//
		// try {
		// // Secure Protocol implementation.
		// SSLContext ctx = SSLContext.getInstance("SSL");
		// // Implementation of a trust manager for X509 certificates
		// X509TrustManager tm = new X509TrustManager() {
		//
		// public void checkClientTrusted(X509Certificate[] xcs,
		// String string) throws CertificateException {
		//
		// }
		//
		// public void checkServerTrusted(X509Certificate[] xcs,
		// String string) throws CertificateException {
		// }
		//
		// public X509Certificate[] getAcceptedIssuers() {
		// return null;
		// }
		// };
		// ctx.init(null, new TrustManager[] { tm }, null);
		// SSLSocketFactory ssf = new SSLSocketFactory(ctx);
		// ClientConnectionManager ccm = httpclient.getConnectionManager();
		// // register https protocol in httpclient's scheme registry
		// SchemeRegistry sr = ccm.getSchemeRegistry();
		// sr.register(new Scheme("https", 443, ssf));
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		//
		// HttpGet httpGet = new HttpGet(
		// "https://test-appimgs.95155.com/MobileFileServer/download.do?p=1F3872FDB1AC3A7B11F9D151B8E86145D15B9D0243F0EF22F360CDB67560F207");
		// // HttpGet httpGet = new HttpGet(
		// //
		// "http://www.sucaitianxia.com/d/file/20131221/13a00e7eb7572a68f320a31ffcac5ad5.png");
		// HttpResponse response = httpclient.execute(httpGet);
		//
		// IOUtils.copy(response.getEntity().getContent(), new FileOutputStream(
		// "D:/monkey/2.jpg"));
		// System.out.println("====================>>>>>>>"
		// +response.getHeaders("Content-Type"));
		// Header[] headers = response.getAllHeaders();
		// for (int i = 0; i < headers.length; i++) {
		// System.out.println(headers[i].getName() + "===>>>" +
		// headers[i].getValue());
		// }
		// /**
		// * Content-Type===>>>image/png
		// * Content-Type===>>>image/jpeg
		// *
		// */
		Map<String, Object> imageStream = getImageStream("https://test-appimgs.95155.com/MobileFileServer/download.do?p=1F3872FDB1AC3A7B11F9D151B8E86145D15B9D0243F0EF22F360CDB67560F207");
		System.out.println(imageStream.get("imageStream"));
		IOUtils.copy((InputStream) imageStream.get("imageStream"), new FileOutputStream(
				 "D:/monkey/1" + imageStream.get("fileExt")));

	}

}
